import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:smooth_scroll_multiplatform/smooth_scroll_multiplatform.dart';
import 'package:suburban_inside_flutter/model/save_info_model.dart';
import 'package:suburban_inside_flutter/viewmodel/general_viewmodel.dart';
import 'package:suburban_inside_flutter/widget/colorful_button.dart';

import '../viewmodel/history_sort_state.dart';
import '../widget/page_wrapper.dart';



class LoadHistoryPage extends StatefulWidget {
  const LoadHistoryPage({super.key});

  @override
  State<LoadHistoryPage> createState() => _LoadHistoryPageState();
}

class _LoadHistoryPageState extends State<LoadHistoryPage> {

  @override
  Widget build(BuildContext context) {
    return PageWrapper(
      title: "Load Actions",
      appBarCustom: ListenableBuilder(
        listenable: GeneralViewModel().historyViewmodel,
        builder: (context, _) {
          return Row(
            // children: GeneralViewModel().historyViewmodel.historySortState.sortTypes.map<Widget>((type) {
            //   return SortTypeButton(type: type);
            // }).toList(),
            children: [
              Padding(
                padding: const EdgeInsets.fromLTRB(10, 0, 6, 0),
                child: ColorfulButton(
                  style: const TextStyle(height: 2.1),
                  fgColorHover: Colors.black,
                  bgColor: Colors.white12,
                  bgColorHover: Colors.white,
                  onTap: () {
                    GeneralViewModel().pushRequest("re_eval").then((_) {
                      GeneralViewModel().historyViewmodel.notify();
                    });
                  },
                  child: const Text("re-eval"),
                ),
              ),

              const Expanded(child: SizedBox.shrink()),

              ...List.generate(
                  GeneralViewModel().historyViewmodel.historySortState.sortTypes.length,
                      (index) {
                    var type = GeneralViewModel().historyViewmodel.historySortState.sortTypes[index];
                    var currentEnableType = GeneralViewModel().historyViewmodel.historySortState.currentSortType;
                    return SortTypeButton(
                      type: type,
                      enable: type==currentEnableType,
                    );
                  }
              ),
            ],
          );
        },
      ),
      child: ListenableBuilder(
        listenable: GeneralViewModel().historyViewmodel,
        builder: (context, _) {
          return FutureBuilder(
            future: GeneralViewModel().historyViewmodel.fetch(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const CircularProgressIndicator();
              }
              else if (snapshot.hasError) {
                return const Center(
                  child: Text("error!"),
                );
              }
              else {
                final temp = GeneralViewModel().historyViewmodel;
                return temp.infos.isNotEmpty
                ? DynMouseScroll(
                    scrollSpeed: 0.86,
                    animationCurve: Curves.easeOutQuart,
                    builder: (context, controller, physics) {
                      return GridView.builder(
                        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 4, // 设置为三列
                          crossAxisSpacing: 10, // 列间距
                          mainAxisSpacing: 10, // 行间距
                          childAspectRatio: 0.86, // 宽高比
                        ),
                        controller: controller,
                        physics: physics,
                        itemCount: temp.infos.length, // 列表项的数量
                        itemBuilder: (context, index) {
                          return SaveCard(
                            info: temp.infos[index],
                          );
                        },
                      );
                    },
                )
                : const Center(
                  child: Text("no data."),
                );
              }
            },
          );
        },
      )
    );
  }
}


class SortTypeButton extends StatelessWidget {
  const SortTypeButton({super.key, required this.type, required this.enable});

  final SortType type;
  final bool enable;

  final double outerLr = 6;
  final double innerLr = 6;
  final double tb = 0;

  @override
  Widget build(BuildContext context) {

    final color = enable
      ? Colors.white : Colors.white38;

    final icon = type.reverse
      ? Icons.keyboard_arrow_down_sharp : Icons.keyboard_arrow_up_sharp;

    return Padding(
      padding: EdgeInsets.fromLTRB(outerLr, tb, outerLr, tb),
      child: MouseRegion(
        cursor: SystemMouseCursors.click,
        child: GestureDetector(
          onTap: () {
            print("sort type '${type.typeName}' tapped");
            GeneralViewModel().historyViewmodel.updateSortType(type);
          },
          child: Container(
            color: Colors.transparent,
            child: Padding(
              padding: EdgeInsets.fromLTRB(innerLr, tb, innerLr, tb),
              child: Row(
                children: [
                  Icon(icon, color: color),
                  Text(type.typeName, style: TextStyle(color: color)),
                ],
              )
            ),
          ),
        ),
      ),
    );
  }
}



class SaveCardMock extends StatelessWidget {
  const SaveCardMock({
    super.key, required this.info});

  final SaveInfo info;

  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}


class SaveCard extends StatefulWidget {
  const SaveCard({
    super.key, required this.info});

  final SaveInfo info;

  @override
  State<SaveCard> createState() => _SaveCardState();
}

class _SaveCardState extends State<SaveCard> {

  final ValueNotifier<bool> _hover = ValueNotifier(false);

  // @override
  // void initState() {
  //   print("debug me");
  //   super.initState();
  // }

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (e) => _hover.value=true,
      onExit: (e) => _hover.value=false,
      child: Container(
        decoration: BoxDecoration(
          color: const Color.fromARGB(255, 237, 237, 237),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: () {
              print("save tapped");
              // Future.delayed(const Duration(milliseconds: 200)).then((_) {
              //   GeneralViewModel().pushRequest("restore ${info.name}");
              //   Navigator.pop(context);
              // });
              GeneralViewModel().pushRequest("restore ${widget.info.name}");
              Navigator.pop(context);
            },
            child: Padding(
              padding: const EdgeInsets.fromLTRB(10, 4, 10, 4),
              child: Stack(
                children: [
                  Center(
                    child: DefaultTextStyle(
                      style: const TextStyle(color: Colors.black, fontSize: 14),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(widget.info.name),
                              // ColorfulButton(child: Text("child"))
                            ],
                          ),

                          AspectRatio(
                            aspectRatio: 1,
                            child: Container(
                              decoration: BoxDecoration(
                                  border: Border.all(
                                      width: 1,
                                      color: Colors.black45
                                  )
                              ),
                              child: Image.memory(
                                GeneralViewModel().historyViewmodel.covers[widget.info.name]!,
                                fit: BoxFit.cover
                              ),
                            ),
                          ),

                          const Expanded(child: SizedBox.shrink()),

                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(widget.info.stepIndex),
                              Text("R:${widget.info.totalReward.toStringAsFixed(2)}"),
                              Text("C:${widget.info.totalCost.toStringAsFixed(2)}"),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),

                  ListenableBuilder(
                    listenable: _hover,
                    builder: (context, _) {
                      return Positioned(
                        right: 4,
                        top: 4,
                        child: AnimatedSwitcher(
                          duration: const Duration(milliseconds: 120),
                          child: _hover.value
                          ? ColorfulButton(
                            key: GlobalKey(),
                            // key: ValueKey(widget.info.name),
                            paddingLR: 6,
                            height: 36,
                            bgColor: Colors.black87,
                            bgColorHover: Colors.redAccent,
                            onTap: () {
                              print("save delete");
                              GeneralViewModel().historyViewmodel.remove(widget.info.name);
                            },
                            child: const Icon(Icons.delete),
                          ) : SizedBox.shrink(
                            // key: ValueKey("blank"),
                            key: GlobalKey(),
                          ),
                        ),
                      );
                    }
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
